package com.example.administrator.appstpremvpdemo.model;

import com.example.administrator.appstpremvpdemo.common.MainApplication;
import com.example.administrator.appstpremvpdemo.contract.AppListContract;
import com.example.administrator.appstpremvpdemo.model.entity.Datebean;
import com.example.administrator.appstpremvpdemo.net.HttpListener;
import com.example.administrator.appstpremvpdemo.net.HttpResponseListener;
import com.example.administrator.appstpremvpdemo.net.JavaBeanRequest;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/4.
 */

public class TasklistBaseModel<T> implements AppListContract.Model<Datebean>, OnResponseListener<Datebean> {

    AppListContract.Presenter<T> mPresenter;
    String mUrl;
    Map<String, String> mParms = new HashMap<>();

    int mCurrentPageIndex = 1;
    int mMaxPageIndex = 1;

    public TasklistBaseModel(AppListContract.Presenter<T> presenter, String url) {
        this.mPresenter = presenter;
        this.mUrl = url;
    }

    @Override
    public void setParms(Map<String, String> parms) {
        mParms = parms;
        if (parms == null) {
            mParms = new HashMap<String, String>();
        }
    }

    @Override
    public void getNextPageData() {
        if (mCurrentPageIndex != mMaxPageIndex) {
            mParms.put("pageIndex", (mCurrentPageIndex + 1) + "");
            mPresenter.start();
        } else {
            mPresenter.noMoreData();
        }
    }

    @Override
    public void start() {
        requestData();
    }

    @Override
    public void destroy() {
        mPresenter = null;
    }

    @Override
    public void requestData() {
        RequestQueue requestQueue = MainApplication.getmRequestQueue();
        JavaBeanRequest<Datebean> request = new JavaBeanRequest<>(mUrl, RequestMethod.GET, Datebean.class);
        request.add(mParms);
        requestQueue.add(1, request, this);
    }

    @Override
    public void downloadapp(String url) {

    }

    @Override
    public void onStart(int what) {
        mPresenter.onstartRequest();
    }

    @Override
    public void onSucceed(int what, Response<Datebean> response) {
        if (response != null && response.get() != null) {
            Datebean datebean = response.get();
            mCurrentPageIndex = datebean.getPageNo();
            mMaxPageIndex = datebean.getMaxPage();
            mPresenter.showApplist(((T) datebean));
        }
    }

    @Override
    public void onFailed(int what, Response<Datebean> response) {
        Exception exception = response.getException();
        mPresenter.handleRequestException(exception);
    }

    @Override
    public void onFinish(int what) {

    }
}
